<?php

namespace app\index\controller;

use app\index\model\Order;
use think\Db;
use app\index\model\pay\H5pay;

/**
 * Created by 二当家的.
 * User: 826096331@qq.com
 * Date: 17-10-18
 * Time: 上午10:35
 */
class Pay extends Base
{
    /**
     * @return array
     * 统一下单接口
     * @author  曹旺
     * @data  15:50
     */
    public function wxH5Pay()
    {
        //return 3;
        $order_id=input('post.order_id');
        $user_id=input('post.user_id');
        //return $order_id;
        $token=input('post.token');
        $key=input('post.sign');
        $value = 'http://www.importndsf.com/import_nbsm/nbsm_shopping/public/index.php/index/Pay/wxH5Pay';
        $sign_pass = $this->encryption($key, $value);
        if (!$sign_pass) {
            $result_json = ['code' => 199, 'msg' => '签名失败', 'content' => '管理员正在处理'];
            return $result_json;
        }
        $token_pass = $this->encryption_token($token);
        if (!$token_pass) {
            $result_json = ['code' => 199, 'msg' => '没有登录', 'content' => '管理员正在处理'];
            return $result_json;
        }
        $order_info=$this->order_info($order_id,$user_id);
        //$money = 1;//充值金额
        //$money=$order_info['money']*100;
        $userip = $this->get_client_ip(); //获得用户设备IP
        //dump($userip);die;
        $appid = "wx292e1491eca7a249";//微信给的appid 1
        $mch_id = "1493550662";//微信官方的mch_id 3
        $key = "9JTOvroPhcxaAnosVXkwGtWlilsCkkOR";//自己设置的微信商家key
        $rand = rand(00000, 99999);
        $out_trade_no = $order_info['order_number'].$rand;// . $rand;//平台内部订单号out_trade_no 6
        $nonce_str = MD5($out_trade_no);//随机字符串nonce_str 4
        //return $nonce_str;die;
        $body = "挪丹瑞芬";//内容body 2
        $total_fee = $order_info['money']*100; //金额total_fee 8
        $time_start=date('YmdHis');
        //return $time_start;
        $time_expire=date('YmdHis', time()+600);
        $attach=$this->attach($order_id,$user_id,$order_info['order_number']);
        $spbill_create_ip = $userip; //IPspbill_create_ip
        $notify_url = "http://www.importndsf.com/import_nbsm/nbsm_shopping/public/index.php/index/pay/notify"; //回调地址notify_url 5
        $trade_type = 'MWEB';//交易类型 具体看API 里面有详细介绍trade_type 9
        $scene_info = '{"h5_info":{"type":"Wap","wap_url":"http://pay.importndsf.com/","wap_name":"挪丹瑞芬"}}';//场景信息 必要参数scene_info 7
        $signA = "appid=$appid&attach=$attach&body=$body&mch_id=$mch_id&nonce_str=$nonce_str&notify_url=$notify_url&out_trade_no=$out_trade_no&scene_info=$scene_info&spbill_create_ip=$spbill_create_ip&time_expire=$time_expire&time_start=$time_start&total_fee=$total_fee&trade_type=$trade_type";
        $strSignTmp = $signA . "&key=$key"; //拼接字符串  注意顺序微信有个测试网址 顺序按照他的来 直接点下面的校正测试 包括下面XML  是否正确
        $sign = strtoupper(MD5($strSignTmp)); // MD5 后转换成大写sign
        //return $sign;
        $post_data = "<xml>
                        <appid>$appid</appid>
                        <attach>$attach</attach>
                        <body>$body</body>
                        <mch_id>$mch_id</mch_id>
                        <nonce_str>$nonce_str</nonce_str>
                        <notify_url>$notify_url</notify_url>
                        <out_trade_no>$out_trade_no</out_trade_no>
                        <scene_info>$scene_info</scene_info>
                        <spbill_create_ip>$spbill_create_ip</spbill_create_ip>
                        <time_expire>$time_expire</time_expire>
                        <time_start>$time_start</time_start>
                        <total_fee>$total_fee</total_fee>
                        <trade_type>$trade_type</trade_type>
                        <sign>$sign</sign>
                    </xml>";//拼接成XML 格式
        $url = "https://api.mch.weixin.qq.com/pay/unifiedorder";//微信传参地址
        $dataxml = $this->http_post($url, $post_data); //后台POST微信传参地址  同时取得微信返回的参数，http_post方法请看下文
        $objectxml = (array)simplexml_load_string($dataxml, 'SimpleXMLElement', LIBXML_NOCDATA); //将微信返回的XML 转换成数组
        //$result_json = ['code' => 200, 'msg' => '请求成功', 'content' => $objectxml];
        //return $result_json;
        if ($objectxml['return_code'] == 'SUCCESS') {
            //return 1;
            if ($objectxml['result_code'] == 'SUCCESS') {//如果这两个都为此状态则返回mweb_url，详情看‘统一下单’接口文档
                //$url_a =  $objectxml['mweb_url'] ;
                $arr['mweb_url']=$objectxml['mweb_url'].'&redirect_url=http%3a%2f%2fwww.importndsf.com%2fhtml%2fpay_success.html'; //mweb_url是微信返回的支付连接要把这个连接分配到前台
                $arr['money']=$order_info['money'];
                $result_json = ['code' => 200, 'msg' => '请求成功', 'content' => $arr];
                return $result_json;
                //echo $objectxml['mweb_url'].'&redirect_url=http%3a%2f%2fwww.importndsf.com%2fimport_nbsm%2feshop%2fhtml%2fpay_success.html'; //mweb_url是微信返回的支付连接要把这个连接分配到前台
            }
            if ($objectxml['result_code'] == 'FAIL') {
                $result_json = ['code' => 199, 'msg' => '签名失败', 'content' => $objectxml['err_code_des']];
                return $result_json;
                //echo $err_code_des = $objectxml['err_code_des'];
            }
        }
    }

    /**
     * @return string
     * 下单的回调函数
     * @author  曹旺
     * @data  15:51
     */
    public function notify(){
        $data = file_get_contents('php://input');
        //文件日志
        Pay::fileLog($data, 'notify.log');
        //自定义参数
        //$data = 'params=eyJ1aWQiOjYsIm9yZGVyTnVtYmVyIjoiVzAzMjMwOTE2NDU2MDA5MSIsIm1ldGhvZCI6ImFsaXBheSJ9&gmt_create=2018-03-23+09%3A23%3A55&charset=UTF-8&gmt_payment=2018-03-23+09%3A23%3A59&notify_time=2018-03-23+09%3A23%3A59&subject=%E4%B8%AD%E5%BD%A7%E7%89%8C%E7%85%A7%E8%AE%A2%E5%8D%95&sign=ViRJXK80%2FtaStPno0BbhIWIceWBrQulFxbWbkvPpa4D%2FqYNLifmw3nANMB%2FdLBeFWO1ojfXClw5tXXXD3M%2Ff1ZqC5UOu2BBK%2BdSfsFphE%2BnhlBpyuLWhmwe80Cz%2FgppONIjI8PsQO4q0EgJ9Qvsd7qICAjiR5YqIcoa3DZjL4rzwkDxxq8UebTPF78KOmVvLz2bvzzV6%2BE5YuJA8No5Lo5eYgunISu0kafuvOaEMBlzE8%2FKsVIVxVCuq55GbBefu7tz1YvEWtHUtuBtHBHcDzJiyN4xXd7hR9OhhYIivz%2FvS8HUhLQSD%2BgGdQ8Kk%2FHRYzNEJIPjPHacG5BwO8QcVdw%3D%3D&buyer_id=2088112217380294&body=%E4%B8%AD%E5%BD%A7%E7%89%8C%E7%85%A7%E8%AE%A2%E5%8D%95&invoice_amount=0.01&version=1.0&notify_id=59e2c9cfaab8e656673bb68821caf3ei8p&fund_bill_list=%5B%7B%22amount%22%3A%220.01%22%2C%22fundChannel%22%3A%22ALIPAYACCOUNT%22%7D%5D&notify_type=trade_status_sync&out_trade_no=W032309164560091&total_amount=0.01&trade_status=TRADE_SUCCESS&trade_no=2018032321001004290559506068&auth_app_id=2018032202425729&receipt_amount=0.01&point_amount=0.00&app_id=2018032202425729&buyer_pay_amount=0.01&sign_type=RSA2&seller_id=2088921759977422';
        $params = $this->decodeParams($this->getNotifyParams($data));
        Pay::fileLog($params, 'params.log');
        $H5Model=new H5pay();
        //$key='9JTOvroPhcxaAnosVXkwGtWlilsCkkOR';
        $result=$H5Model->notify($data,$params);
        return $result;

    }

    /**
     * @return array
     *支付成功后查看订单状态
     * @author  曹旺
     * @data  11:06
     */
    public function order_state(){
        $order_id=input('post.order_id');
        $user_id=input('post.user_id');
        $key=input('post.sign');
        $token=input('post.token');
        $value = 'http://www.importndsf.com/import_nbsm/nbsm_shopping/public/index.php/index/Pay/order_state';
        $sign_pass = $this->encryption($key, $value);
        if (!$sign_pass) {
            $result_json = ['code' => 199, 'msg' => '签名失败', 'content' => '管理员正在处理'];
            return $result_json;
        }
        $token_pass = $this->encryption_token($token);
        if (!$token_pass) {
            $result_json = ['code' => 199, 'msg' => '没有登录', 'content' => '管理员正在处理'];
            return $result_json;
        }
        $order_model=new Order();
        $res=$order_model->order_state($order_id,$user_id);
        if ($res){
            if ($res['order_state']==1){
                $result_json = ['code' => 200, 'msg' => '订单未支付', 'content' => $res];
                return $result_json;
            }elseif ($res['order_state']==2){
                $result_json = ['code' => 200, 'msg' => '订单已支付', 'content' => $res];
                return $result_json;
            }elseif ($res['order_state']==3){
                $result_json = ['code' => 200, 'msg' => '订单已发货', 'content' => $res];
                return $result_json;
            }else{
                $result_json = ['code' => 200, 'msg' => '订单已收货', 'content' => $res];
                return $result_json;
            }
        }else{
            $result_json = ['code' => 199, 'msg' => '订单不存在', 'content' => '不存在的订单'];
            return $result_json;
        }

    }
    /**
     * @param $order_id
     * @param $user_id
     * @return array|false|mixed|\PDOStatement|string|\think\Model
     * 获取订单金额和订单号
     * @author  曹旺
     * @data  15:52
     */

    public function order_info($order_id,$user_id){
        $order_info=Db::table('nbsm_order')->field('money,order_number')->where(['id'=>$order_id,'user_id'=>$user_id])->find();
        return $order_info;
    }

    /**
     * @param $data微信传的参数（下单时自定义的参数）
     * @return \SimpleXMLElement[]|string
     * 获取通知数据
     * @author  曹旺
     * @data  15:52
     */
    public function getNotifyParams($data){
        $xml_parser = xml_parser_create();
        if(!xml_parse($xml_parser,$data,true)){
            //支付宝数据
            parse_str($data, $data);
            $params = urldecode($data['params']);
        }else {
            //微信数据
            $obj = simplexml_load_string($data);
            $params = $obj->attach;

        }
        return $params;
    }

    /**
     * 编码自定义参数
     */
    public function attach($order_id,$user_id,$order_number){
        return base64_encode(json_encode(['user_id'=>$user_id,'order_id'=>$order_id,'order_number'=>$order_number]));
            //return base64_encode(json_encode(['uid'=>$this->uid, 'orderNumber'=>$this->orderNumber, 'method'=>$this->method]));
    }

    /**
     * 解码自定义参数
     * author caowang.
     * date 2018/3/22
     */
    public static function decodeParams($params){
        return json_decode(base64_decode($params), true);
    }

}
